import axios from 'axios'
import { Message } from 'element-ui'
import Variables from './variables'
import Cookies from 'js-cookie'

// 设置请求头
axios.defaults.headers.common['Authorization'] = Cookies.get('Admin-Token');
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.common['userId'] = Cookies.get('userId');

console.log(this)

// 拦截请求返回数据，将14位及以上的数字number转成string类型
axios.defaults.transformResponse = [function(data) {
  if(typeof data === 'string') {
    try {
      let d = data;
      let array = d.match(/:\d{14}\d*/g);
      if(array === null){
        data = JSON.parse(data);
        return data
      }
      // 遍历所有查找14位以上的数字，将其number拼装为string
      for (var i = 0; i < array.length; i++) {
        let str = array[i];
        let number = str.replace(":", "");
        d = d.replace(str, ':"' + number + '"')
      }
      data = JSON.parse(d);
    } catch(e){}
  }
  return data;
}]

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 10000,
})
// request interceptor
service.interceptors.request.use(
  config => {
    const log = JSON.parse(JSON.stringify(config))
    console.log('url：'+log.baseURL + log.url +' | type：'+ log.method +' | params：')
    console.log(log.data)
    return config
  },
  error => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    const res = response.data
    console.log(response.response)
    if(response.response.status === 400){

    }else if (response.response.status === 401) {

    }else if (response.response.status === 500) {

    }else if(response.response.status !== 20000 && response.response.status !== 200){

      return Promise.reject('error')
    } else {
      return response.data
    }
   },
  error => {
    return Promise.reject(error)
  }
)

export default service
